<?php

/**
 * @author kingop
 */
class AccountController extends CustomControllerAction {

    public function preDispatch() {
        parent::preDispatch();

        if (isset(Zend_Auth::getInstance()->getIdentity()->id)) {
            $userId = Zend_Auth::getInstance()->getIdentity()->id;
            if (!$userId) $this->_redirect($this->getUrl('login'));
            $user = new DatabaseObject_User($this->db);
            $user->load($userId);
            if ($user->nameshop != '') {
                $shop = new DatabaseObject_Shop($this->db);
                $shop->load($userId);
                $pay = $this->db->fetchAll("SELECT * FROM `pay` WHERE `userId`='$userId' and flag='1' ORDER BY id ASC LIMIT 1");
                
                if (strtotime($shop->data_end) < strtotime(date("Y-m-d H:i:s"))) {
                if ($pay[0])
                {
                    $tarif = new DatabaseObject_Tarif($this->db);
                    $tarif->load($pay[0]['tarif']);
                    $pid = $pay[0]['id'];
                    $shop->plimit = $tarif->count_product;
                    $shop->payflag = '1';
                    $shop->data_end =  date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s'))) . " +" . $pay[0]['month'] . " month"));
                    $shop->save();
                    $this->db->query("UPDATE `pay` SET flag='0' WHERE `userId`='$userId' and id='$pid'");
                }
            else{
              
                    $shop->plimit = '5';
                    $shop->payflag = '0';
                    $shop->data_end = '0000-00-00 00:00:00';
                    $shop->save();
                }
                
            }
            }
            $this->view->user = $user;
        }
    }

    public function postDispatch() {
        parent::postDispatch();

        if (isset(Zend_Auth::getInstance()->getIdentity()->id))
            $userId = Zend_Auth::getInstance()->getIdentity()->id;
    }

    public function indexAction() {

        $this->view->page_title = "Пользователь";
        $auth = Zend_Auth::getInstance();
        // CustomControllerAction::pre($auth->getIdentity());
        if (!$auth->getIdentity()->id)
            $this->_redirect($this->getUrl('login'));
        $this->view->usermenu = 'index';
    }

    public function registerAction() {
        $this->view->page_title = "Регистрация";
        $this->view->widget = '1';
        if (!$cats = $this->cache->load('leftcat')) {
            // промах кэша
            $cats = DatabaseObject_Categories::GetAllParent($this->db);
            $this->cache->save($cats, 'leftcat');
        } else {
            // попадание в кэш
        }
        $this->view->categories = $cats;
        $request = $this->getRequest();
        $fp = new FormProcessor_UserRegistration($this->db);


        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                $session = new Zend_Session_Namespace('registration');
                $session->user_id = $fp->user->getId();
                $this->_redirect($this->getUrl('registercomplete'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }
        $this->view->fp = $fp;
        $temp = CustomControllerAction::getCountry();
        $this->view->countrylist = $temp['country'];
        $this->view->pravila = $this->configuration['pravila'];
    }

    public function registercompleteAction() {
        $this->view->page_title = "Регистрация прошла успешно";
        $session = new Zend_Session_Namespace('registration');

        // загрузим данные о пользователе по его ID
        $user = new DatabaseObject_User($this->db);
        if (!$user->load($session->user_id)) {
            $this->_forward('register');
            return;
        }

        // отправим email-ы админам, чтобы сообщить им о новой регистрации
        $emails = $this->configuration['admin_email'];
        $subject = $this->configuration['admin_reg_subject'];

        $link_to_view_user = '<a href="http://' . $_SERVER['SERVER_NAME'] . '/admin/users/edit/' . $user->getId() . '">Просмотреть пользователя</a>';
        $text = preg_replace('/%userlink%/', $link_to_view_user, $this->configuration['admin_reg_text']);

        /* Для отправки HTML-почты вы можете установить шапку Content-type. */
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";

        /* дополнительные шапки */
        $headers .= "From: . Торговая площадка\r\n";


        mail($emails, $subject, $text, $headers);

        $message = sprintf('Зарегистрирован пользователь  %s', $user->login);

        $this->writeLog($message);

        $activation_link = 'http://' . $_SERVER['SERVER_NAME'] . $this->getUrl('activate', 'utility') . '?hash=' . $user->hash;

        // отправим пользователю письмо с уведомлением об успешной регистрации
        $subject = preg_replace("/%username%/", $user->login, $this->configuration['email_reg_subject']);
        $text = preg_replace('/%username%/', $user->login, $this->configuration['email_reg_text']);
        $text = preg_replace('/%activation_link%/', $activation_link, $this->configuration['email_reg_text']);

        mail($user->email, $subject, $text, $headers);

        $this->view->user = $user;
        if ($_SESSION['cart']) {
            foreach ($_SESSION['cart'] as $k => $v)
                foreach ($v as $kk => $vv)
                    CustomControllerAction::SessionFormDb($kk, vv);
            unset($_SESSION['cart']);
        }
    }

    public function loginAction() {
        $this->view->page_title = "Вход на сайт";
        $this->view->widget = '1';
        if (!$cats = $this->cache->load('leftcat')) {
            // промах кэша
            $cats = DatabaseObject_Categories::GetAllParent($this->db);
            $this->cache->save($cats, 'leftcat');
        } else {
            // попадание в кэш
        }
        $this->view->categories = $cats;
        // если пользователь уже залогинен, отправим его на главную страницу
        $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity())
            $this->_redirect($this->getUrl('index', 'index'));

        $request = $this->getRequest();

        // определим страницу с которой пользователь пришёл
        $redirect = $request->getPost('redirect');
        if (strlen($redirect) == 0)
            $redirect = $request->getServer('REQUEST_URI');
        if (strlen($redirect) == 0)
            $redirect = $this->getUrl();

        // инициализируем массиа для хранения ошибок
        $errors = array();

        // если была отправлена форма, попробуем залогиниться
        if ($request->isPost()) {

            // проверим данные из формы и проверим их
            $login = $request->getPost('login');
            $password = $request->getPost('password');

            if (strlen($login) == 0)
                $errors['login'] = 'Поле "Логин" должно быть заполнено';
            if (strlen($password) == 0)
                $errors['password'] = 'Поле "Пароль" должно быть заполнено';

            //  if (!DatabaseObject_User::IsApproved($this->db, $login))
            //       $errors['login'] = 'Ваша учетная запись еще не прошла модерацию. Как только наши модераторы проверят вашу информацию, вы сможете выполнить вход под своей учетной записью. Об этом вам будет сообщено по email.';

            if (count($errors) == 0) {

                // подключим адаптер авторизации
                $adapter = new Zend_Auth_Adapter_DbTable($this->db, 'users', 'login', 'password', 'md5(?)');

                $adapter->setIdentity($login);
                $adapter->setCredential($password);

                // попытаемся идентифицировать пользователя
                $result = $auth->authenticate($adapter);

                if ($result->isValid()) {
                    $user = new DatabaseObject_User($this->db);
                    $user->load($adapter->getResultRowObject()->id);

                    /* if ($user->isApproved == 0) {
                      $errors['login'] = 'Ваша учетная запись еще не прошла модерацию. Как только наши модераторы проверят вашу информацию, вы сможете выполнить вход под своей учетной записью. Об этом вам будет сообщено по email.';
                      } else { */
                    // создадим сессионные данные и запишем их в сессию
                    $identity = $user->createAuthIdentity();
                    $auth->getStorage()->write($identity);
                    $user->date_last = date('Y-m-d H:i:s');
                    $user->save();
                    $message = sprintf('Успешная авторизация пользователя  %s', $user->login);
                    $this->writeLog($message);
                    foreach ($_SESSION['cart'] as $k => $v)
                        foreach ($v as $kk => $vv)
                            CustomControllerAction::SessionFormDb($kk, $vv);
                    unset($_SESSION['cart']);
                    // вернем пользователяна исходную страницу
                    $this->_redirect($redirect);
                    //}
                } else {
                    $errors['login'] = 'Неверная пара логин/пароль';

                    $message = sprintf('Неуспешная попытка авторизации пользователя  %s', $login);

                    $this->writeLog($message);
                }
            }
        }

        $this->view->errors = $errors;
        $this->view->redirect = $redirect;
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect($this->getUrl('login'));
    }

    public function fetchpasswordAction() {
        $this->view->page_title = "Восстановление пароля";
        // если пользователь уже вошел, перенаправим его на главную страницу
        if (Zend_Auth::getInstance()->hasIdentity())
            $this->_redirect($this->getUrl('index', 'index'));

        $errors = array();

        $action = $this->getRequest()->getQuery('action');

        if ($this->getRequest()->isPost())
            $action = 'submit';

        switch ($action) {
            case 'submit':
                $login = trim($this->getRequest()->getPost('login'));
                if (strlen($login) == 0) {
                    $errors['login'] = 'Поле должно быть заполнено';
                } else {
                    $user = new DatabaseObject_User($this->db);
                    if ($user->load($login, 'login')) {
                        $user->fetchPassword();
                        $url = $this->getUrl('fetchpassword') . '?action=complete';

                        $message = sprintf('Запрос нового пароля пользователем  %s', $user->login);

                        $this->writeLog($message);

                        $this->_redirect($url);
                    } else
                        $errors['login'] = 'Пользователь с указанным логином не найден.';
                }
                break;

            case 'complete':
                break;
        }

        $this->view->errors = $errors;
        $this->view->action = $action;
    }

    public function editprofileAction() {
        $this->view->page_title = "Редактирование профиля";
        $auth = Zend_Auth::getInstance();

        $fp = new FormProcessor_EditProfile($this->db, $auth->getIdentity()->id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                $auth->getStorage()->write($fp->user->createAuthIdentity());

                $message = sprintf('Изменение личных данных пользователем  %s', $user->login);

                $this->writeLog($message);

                $this->_redirect($this->getUrl('editprofilecomplete'));
            }
        }
        $temp = CustomControllerAction::getCountry();
        $this->view->countrylist = $temp['country'];

        $temp = CustomControllerAction::getRegion($fp->country_id);

        $this->view->regionlist = $temp['regions'];
        $temp = CustomControllerAction::getCity($fp->region_id);

        $this->view->citylist = $temp['citys'];
        $this->view->fp = $fp;
        $this->view->usermenu = 'editprofile';
    }

    public function editprofilecompleteAction() {
        $this->view->page_title = "Редактирование профиля";
        $user = new DatabaseObject_User($this->db);
        $user->load(Zend_Auth::getInstance()->getIdentity()->id);

        $this->view->user = $user;
        $this->view->usermenu = 'editprofile';
    }

    public function activateAction() {
        $hash = $this->getRequest()->getParam('hash');

        $user = new DatabaseObject_User($this->db);
        $user->load($hash, 'hash');
        $user->isActivated = 1;
        $user->save();
    }

    /////////////////////// PRODUCTS ACTION ///////////////////////   
    public function productsAction() {
        $this->view->page_title = "Мои продукты";
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['products_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['products_sort'])) {
            $temp = explode(' ', $_SESSION['products_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'name';
            $order = 'asc';
            $_SESSION['products_sort'] = $sort . ' ' . $order;
        }
        $page = max(1, $this->getRequest()->getQuery('p'));
        $type = $this->getRequest()->getParam('type');

        $limit = $this->configuration['item_count'];
        $offset = ($page - 1) * $limit;
        $filter = array(
            'type' => $type,
            'userId' => Zend_Auth::getInstance()->getIdentity()->id
        );
        $pages = ceil(DatabaseObject_Products::GetProductsCount($this->db, array('order' => $_SESSION['products_sort']), $filter) / $limit);
        $products = DatabaseObject_Products::GetProducts($this->db, array('order' => $_SESSION['products_sort'], 'limit' => $limit, 'offset' => $offset), $filter);
        $cats = DatabaseObject_Categories::GetCategories($this->db);
        $this->view->cats = $cats;
        $pag = CustomControllerAction::Pag($pages, $page);
        $this->view->pages = $pag;
        $this->view->products = $products;
        $this->view->p = $page;
        $this->view->type = $type;
        $this->view->sort = $sort;
        $this->view->order = $order;
    }

    public function addfileAction() {

        ////Загрузка 
        if ($_FILES['upload']) {
            $upl = @$_FILES['upload'];
            $ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
            $ufilename = time() . '.' . $ext;
            $path = DatabaseObject_ProductsImg::GetUploadDirectory();
            $filename = $ufilename;
            $file = $path . '/' . $filename;
            if (move_uploaded_file($_FILES['upload']['tmp_name'], $file)) {
                list($w, $h) = getimagesize($file);
                $_SESSION['newRatio'] = ((float) $w / 200);
                echo $filename;
            } else {
                echo "error";
            }
        }
        exit;
    }

    public function addlogoAction() {

        ////Загрузка 
        if ($_FILES['upload']) {
            $upl = @$_FILES['upload'];
            $ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
            $ufilename = time() . '.' . $ext;
            $path = Zend_Registry::get('config')->paths->base . "/www/uploads/tmp";
            $filename = $ufilename;
            $file = $path . '/' . $filename;
            if (move_uploaded_file($_FILES['upload']['tmp_name'], $file)) {
                list($w, $h) = getimagesize($file);
                $_SESSION['newRatio'] = ((float) $w / 200);
                echo $filename;
            } else {
                echo "error";
            }
        }
        exit;
    }

    public function ajaxfileAction() {

        ////Загрузка 
        $img = $_POST['file'];
        $path = Zend_Registry::get('config')->paths->base . "/www/uploads/";
        $src = $path . '/' . $img;
        $src1 = $path . 'logo/' . $img;
        $src2 = '/uploads/logo/' . $img;
        list($w_i, $h_i, $type) = getimagesize($src);
        $types = array('', 'gif', 'jpeg', 'png');
        $ext = $types[$type];
        $func = 'imagecreatefrom' . $ext;
        $func1 = 'image' . $ext;
        $img_r = $func($src);
        if ($_SESSION['newRatio'] != '') {
            $x1 = $_POST['x1'] * $_SESSION['newRatio'];
            $y1 = $_POST['y1'] * $_SESSION['newRatio'];
            $h = $_POST['h'] * $_SESSION['newRatio'];
            $w = $_POST['w'] * $_SESSION['newRatio'];
            $x2 = $_POST['x2'] * $_SESSION['newRatio'];
            $y2 = $_POST['y2'] * $_SESSION['newRatio'];
            $dst_r = ImageCreateTrueColor($w, $h);
            imagecopyresampled($dst_r, $img_r, 0, 0, $x1, $y1, $w, $h, $w, $h);
        } else {
            $x1 = $_POST['x1'];
            $y1 = $_POST['y1'];
            $h = $_POST['h'];
            $w = $_POST['w'];
            $x2 = $_POST['x2'];
            $y2 = $_POST['y2'];
            $dst_r = ImageCreateTrueColor($w, $h);
            imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x1'], $_POST['y1'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
        }
        $func1($dst_r, $src1);
        unlink($src);
        $logo = new DatabaseObject_User($this->db);
        $logo->load(Zend_Auth::getInstance()->getIdentity()->id);
        unlink(Zend_Registry::get('config')->paths->base . "/www/" . $logo->photo);
        $logo->photo = $src2;
        $logo->save();
        exit;
    }

    public function deletefileAction() {

        ////Загрузка 
        $filename = $this->getRequest()->getPost(id);
        $id = explode('-', $filename);

        $path = DatabaseObject_ProductsImg::GetUploadDirectory();
        $file = $path . '/' . $filename;
        DatabaseObject_ProductsImg::DeleteProductsImgFilename($this->db, $filename);
        if (file_exists($file)) {
            if (unlink($file)) {

                echo 'yes';
            } else {
                echo "error";
            }
        } else {
            echo 'error1';
        }
        exit;
    }

    public function deletelogoAction() {

        ////Загрузка 
        $filename = $this->getRequest()->getPost(id);
        $logo = new DatabaseObject_User($this->db);
        $logo->load(Zend_Auth::getInstance()->getIdentity()->id);

        // $id = explode('-', $filename);

        $path = Zend_Registry::get('config')->paths->base . "/www";
        $file = $path . $logo->photo;
        // DatabaseObject_ProductsImg::DeleteProductsImgFilename($this->db, $filename);
        if (file_exists($file)) {
            if (unlink($file)) {

                echo 'yes';
                $logo->photo = '';
                $logo->save();
            } else {
                echo "error";
            }
        } else {
            echo 'error1';
        }
        exit;
    }

    public function uploadAction() {
        $allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
        // max file size in bytes
        $sizeLimit = 1 * 1024 * 1024;
        include 'QqUploadedFileXhr.php';
        $uploader = new QqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload(Zend_Registry::get('config')->paths->base . "/www/uploads/", TRUE);
        //print_r($result);
        // to pass data through iframe you will need to encode all html tags

        if (isset($result['success']) && $result['success']) {
            $file = $result['file'];
            $result['url'] = $file;
            $result['url'] = str_replace(Zend_Registry::get('config')->paths->base . "/www", '', $result['url']);
            unset($result['file']);

            $imgsize = getimagesize($file);
            $_SESSION['imgrate'] = ((float) $imgsize[0] / 200);


            $result['width'] = 200;
            $result['height'] = 'auto';
        }

        echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        exit;
    }

    public function cropAction() {

        $x1 = $this->getRequest()->getPost('x1') * $_SESSION['imgrate'];
        $y1 = $this->getRequest()->getPost('y1') * $_SESSION['imgrate'];
        $x2 = $this->getRequest()->getPost('x2') * $_SESSION['imgrate'];
        $y2 = $this->getRequest()->getPost('y2') * $_SESSION['imgrate'];

        $tw = $this->getRequest()->getPost('target_width') * $_SESSION['imgrate'];
        $th = $this->getRequest()->getPost('target_height') * $_SESSION['imgrate'];

        $url = $this->getRequest()->getPost('url');
        $file = Zend_Registry::get('config')->paths->base . "/www" . $url;

        $pi = pathinfo($file);
        list($w_i, $h_i, $type) = getimagesize($file);
        $types = array('', 'gif', 'jpeg', 'png');
        $ext = $types[$type];
        $func = 'imagecreatefrom' . $ext;
        $func1 = 'image' . $ext;
        if (!file_exists($pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login)) {
            mkdir($pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login, 0755);
        }
        $cropped_file = $pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login . '/' . time() . '_' . $tw . 'x' . $th . '.jpg';

        $cropped = imagecreatetruecolor($tw, $th);

        $original = file_get_contents($file);
        $original = imagecreatefromstring($original);

        imagecopyresampled($cropped, $original, 0, 0, $x1, $y1, $tw, $th, $x2 - $x1, $y2 - $y1);
        $func1($cropped, $cropped_file, 80);
        unlink($file);
        $result = array(
            'success' => true,
            'url' => str_replace(Zend_Registry::get('config')->paths->base . "/www", '', $cropped_file),
            'width' => $tw,
            'height' => $th
        );
        echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        exit;
    }

    public function addlogotestAction() {

        $x1 = $this->getRequest()->getPost(x1) * $_SESSION['imgrate'];
        $y1 = $this->getRequest()->getPost(y1) * $_SESSION['imgrate'];
        $x2 = $this->getRequest()->getPost(x2) * $_SESSION['imgrate'];
        $y2 = $this->getRequest()->getPost(y2) * $_SESSION['imgrate'];

        $tw = $this->getRequest()->getPost(target_width) * $_SESSION['imgrate'];
        $th = $this->getRequest()->getPost(target_height) * $_SESSION['imgrate'];

        $url = $this->getRequest()->getPost(url);
        $file = Zend_Registry::get('config')->paths->base . "/www" . $url;

        $pi = pathinfo($file);
        list($w_i, $h_i, $type) = getimagesize($file);
        $types = array('', 'gif', 'jpeg', 'png');
        $ext = $types[$type];
        $func = 'imagecreatefrom' . $ext;
        $func1 = 'image' . $ext;
        if (!file_exists($pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login)) {
            mkdir($pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login, 0755);
            mkdir($pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login . '/logo', 0755);
        } elseif (!file_exists($pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login . '/logo')) { {
                mkdir($pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login . '/logo', 0755);
            }
        }
        $cropped_file = $pi['dirname'] . '/' . Zend_Auth::getInstance()->getIdentity()->login . '/logo/' . time() . '_' . $tw . 'x' . $th . '.jpg';

        $cropped = imagecreatetruecolor($tw, $th);

        $original = file_get_contents($file);
        $original = imagecreatefromstring($original);

        imagecopyresampled($cropped, $original, 0, 0, $x1, $y1, $tw, $th, $x2 - $x1, $y2 - $y1);
        $func1($cropped, $cropped_file, 80);
        unlink($file);
        $result = array(
            'success' => true,
            'url' => str_replace(Zend_Registry::get('config')->paths->base . "/www", '', $cropped_file),
            'width' => $tw,
            'height' => $th
        );
        echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        exit;
    }

    public function addproductsAction() {
        $this->view->page_title = "Добавление продукта";
        $request = $this->getRequest();
        $shop = new DatabaseObject_Shop($this->db);
        $shop->load(Zend_Auth::getInstance()->getIdentity()->id);

        if (Zend_Auth::getInstance()->getIdentity()->type == 'member') {
            if ($shop->plimit <= DatabaseObject_Products::GetCountUser($this->db, Zend_Auth::getInstance()->getIdentity()->id)) {
                $this->view->plimit = '1';
            }
        }

        $fp = new FormProcessor_Products($this->db);

        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                $id = $fp->products->getId();
                $message = sprintf('Добавлена продукт "%s" пользователем "%s"', $fp->category->name, Zend_Auth::getInstance()->getIdentity()->login);
                $this->writeLog($message);
                $this->_redirect($this->getUrl('products'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }

        $this->view->fp = $fp;

        $this->view->cats = DatabaseObject_Categories::GetAllParent($this->db);
    }

    public function editproductsAction() {
        $this->view->page_title = "Редактирование продукта";
        $id = $this->getRequest()->getParam('id');

        $fp = new FormProcessor_Products($this->db, $id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                $message = sprintf('Изменена информация о продукте "%s" пользователем "%s"', $fp->tender->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);

                $this->_redirect($this->getUrl('products'));
            }
        }

        $this->view->cats = DatabaseObject_Categories::GetCategories($this->db);

        $this->view->fp = $fp;
    }

    public function deleteproductsAction() {
        $id = $this->getRequest()->getParam('id');
        $products = new DatabaseObject_Products($this->db);
        $products->load($id);
        if ($products->getId())
            $products->delete();
        unset($products);
        echo 'ok';
        exit;
    }

    ///////////////////////////////////////////////////////////////////
    /////////// Конец работы с продуктами /////////////////////////////
    ///////////////////////////////////////////////////////////////////
    public function reviewsAction() {
        $this->view->page_title = "Отзывы";
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['reviews_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['reviews_sort'])) {
            $temp = explode(' ', $_SESSION['reviews_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'date';
            $order = 'desc';
            $_SESSION['reviews_sort'] = $sort . ' ' . $order;
        }
        $type = $this->getRequest()->getParam('type');
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['item_count'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_ShopReviews::GetShopReviewsCount($this->db, Zend_Auth::getInstance()->getIdentity()->id, $type) / $limit);
        $category = DatabaseObject_ShopReviews::GetShopReviews($this->db, Zend_Auth::getInstance()->getIdentity()->id, $limit, $offset, $type);
        // CustomControllerAction::pre($category);
        $pag = CustomControllerAction::Pag($pages, $page);
        $this->view->pages = $pag;
        $this->view->p = $page;
        $this->view->type = $type;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->categories = $category;
    }

    ///////////////////////////////////////////////////////////////////
    /////////// Начало работы с настройками  //////////////////
    ///////////////////////////////////////////////////////////////////
    public function settingAction() {
        $this->view->page_title = "Настроки профиля";
        $stat = $this->getRequest()->getPost('currency');
        $ntSettings = new DatabaseObject_NotificationSettings($this->db);
        if(!$ntSettings->load(Zend_Auth::getInstance()->getIdentity()->id, 'idUser')) {
            $this->view->nt = false;
        }
        else {
            $this->view->nt = $ntSettings;
        }
        if ($stat) {

            $logo = $this->getRequest()->getPost('logo');


            $cur = new DatabaseObject_User($this->db);
            $cur->load(Zend_Auth::getInstance()->getIdentity()->id);
            $cur->currency = $stat;
            $cur->photo = $logo;
            $cur->save();
            Zend_Auth::getInstance()->getIdentity()->currency = $stat;
            $tmp = $this->db->fetchOne("SELECT name FROM currency WHERE id='$stat'");
            $_SESSION['currency'] = $tmp;
            $this->pre($this->getRequest()->getPost());
            if($this->getRequest()->isPost()) {
                // начало работы с уведомлениями
                $notificationSettings = new DatabaseObject_NotificationSettings($this->db);
                if(!$notificationSettings->load(Zend_Auth::getInstance()->getIdentity()->id, 'idUser')) {
                    // таких настроек еще нет у пользователя, создадим их
                    $notificationSettings->idUser = Zend_Auth::getInstance()->getIdentity()->id;
                    $notificationSettings->new_pm = $this->getRequest()->getPost('new_pm') !== null ? 1 : 0;
                    $notificationSettings->new_com = $this->getRequest()->getPost('new_com') !== null ? 1 : 0;
                    $notificationSettings->new_req = $this->getRequest()->getPost('new_req') !== null ? 1 : 0;
                    $notificationSettings->acc_req = $this->getRequest()->getPost('acc_req') !== null ? 1 : 0;
                    $notificationSettings->new_order = $this->getRequest()->getPost('new_order') !== null ? 1 : 0;
                }
                else {
                    // настройки уведомлений у пользователя уже есть, обновим их
                    $notificationSettings->new_pm = $this->getRequest()->getPost('new_pm') !== null ? 1 : 0;
                    $notificationSettings->new_com = $this->getRequest()->getPost('new_com') !== null ? 1 : 0;
                    $notificationSettings->new_req = $this->getRequest()->getPost('new_req') !== null ? 1 : 0;
                    $notificationSettings->acc_req = $this->getRequest()->getPost('acc_req') !== null ? 1 : 0;
                    $notificationSettings->new_order = $this->getRequest()->getPost('new_order') !== null ? 1 : 0;
                }

                $notificationSettings->save();
            }
            // конец работы с уведомлениями
            
            
            /* echo 'ok';
              exit; */
            $this->_redirect($this->getUrl('setting'));
        }
        $this->view->curr = $this->db->fetchAll("SELECT * FROM currency");
    }

    public function settingshopAction() {
        $this->view->page_title = "Настройки магазина";
        $requests = $this->getRequest();

        /*    $shop = new DatabaseObject_Shop($this->db);
          $shop->load(Zend_Auth::getInstance()->getIdentity()->id);

          $shop->pc2 = $this->getRequest()->getQuery('PC2'); */
        $fp = new FormProcessor_SettingShop($this->db, Zend_Auth::getInstance()->getIdentity()->id);

        if ($this->getRequest()->isPost()) {
            if ($fp->process($this->getRequest())) {
                $message = sprintf('Изменена информация о магазине "%s" пользователем "%s"', $fp->shop->name, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);

                $this->_redirect($this->getUrl('settingshop'));
            }
        }
        $this->view->fp = $fp;
    }

    ///////////////////////////////////////////////////////////////////
    /////////// Конец настройки  //////////////////////////////
    ///////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////
    /////////// Начало работы с друзьями //////////////////////////////
    ///////////////////////////////////////////////////////////////////

    public function friendsAction() {
        $this->view->page_title = "Друзья";
        $id = Zend_Auth::getInstance()->getIdentity()->id;

        $friends = DatabaseObject_Friends::GetUserFriends($this->db, $id);
        $this->view->friends = $friends;

        $friendsCount = DatabaseObject_Friends::GetFriendsCount($this->db, $id);
        $this->view->friendsCount = $friendsCount;
    }

    public function requestsAction() {
        $this->view->page_title = "Заявки в друзья";
        $id = Zend_Auth::getInstance()->getIdentity()->id;

        $requests = DatabaseObject_Friends::GetRequests($this->db, $id);
        $this->view->requests = $requests;

        $requestsCount = DatabaseObject_Friends::GetRequestsCount($this->db, $id);
        $this->view->requestsCount = $requestsCount;
    }

    public function ownrequestsAction() {
        $this->view->page_title = "Заявки в друзья";
        $id = Zend_Auth::getInstance()->getIdentity()->id;

        $requests = DatabaseObject_Friends::GetOwnRequests($this->db, $id);
        $this->view->requests = $requests;

        $ownRequestsCount = DatabaseObject_Friends::GetOwnRequestsCount($this->db, $id);
        $this->view->ownRequestsCount = $ownRequestsCount;
    }

    public function approveallrequestsAction() {
        $id = Zend_Auth::getInstance()->getIdentity()->id;

        DatabaseObject_Friends::ApproveAllRequests($this->db, $id);

        $this->_redirect('friends');
    }

    public function declineallrequestsAction() {
        $id = Zend_Auth::getInstance()->getIdentity()->id;

        DatabaseObject_Friends::DeclineAllRequests($this->db, $id);

        $this->_redirect($this->getUrl('friends'));
    }

    public function approverequestAction() {
        $id = $this->getRequest()->getParam('id');

        DatabaseObject_Friends::ApproveRequest($this->db, $id, Zend_Auth::getInstance()->getIdentity()->id);
    }

    public function declinerequestAction() {
        $id = $this->getRequest()->getParam('id');

        DatabaseObject_Friends::DeclineRequest($this->db, $id, Zend_Auth::getInstance()->getIdentity()->id);
    }

    public function deletefriendAction() {
        $id = $this->getRequest()->getParam('id');

        DatabaseObject_Friends::RemoveFriend($this->db, $id, Zend_Auth::getInstance()->getIdentity()->id);

        $this->_redirect($this->getUrl('friends'));
    }

    public function declinedrequestsAction() {
        $requests = DatabaseObject_Friends::GetDeclinedRequests($this->db, Zend_Auth::getInstance()->getIdentity()->id);
        $this->view->requests = $requests;

        $this->view->declinedRequestCount = DatabaseObject_Friends::GetDeclinedRequestsCount($this->db, $this->db, Zend_Auth::getInstance()->getIdentity()->id);
    }

    public function cancelrequestAction() {
        DatabaseObject_Friends::CancelRequest($this->db, Zend_Auth::getInstance()->getIdentity()->id, $this->getRequest()->getParam('id'));
    }

    public function cancelallrequestsAction() {
        DatabaseObject_Friends::CancelAllRequests($this->db, Zend_Auth::getInstance()->getIdentity()->id);
    }

    ///////////////////////////////////////////////////////////////////
    /////////// Конец работы с друзьями ///////////////////////////////
    ///////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////
    /////////// начало работы с сообщениями ///////////////////////////
    ///////////////////////////////////////////////////////////////////

    public function messagesAction() {
        $this->view->page_title = "Диалоги";
        $limit = 1000;
        $offset = 0;
        $dialogs = DatabaseObject_Pm::GetUserDialogs($this->db, Zend_Auth::getInstance()->getIdentity()->id, $limit, $offset);

        $this->view->dialogs = $dialogs;
    }

    public function viewdialogAction() {
        $this->view->page_title = "Просмотр диалога";
        $limit = 1000;
        $offset = 0;

        $dialog = DatabaseObject_Pm::GetDialog(
                        $this->db, Zend_Auth::getInstance()->getIdentity()->id, $this->getRequest()->getParam('id'), $limit, $offset
        );

        $this->view->dialog = $dialog;
        $user = new DatabaseObject_User($this->db);
        $user->load($this->getRequest()->getParam('id'));
        $this->view->dialogger = $user;

        // пометим диалог прочитанным
        DatabaseObject_Pm::MarkDialogAsRead($this->db, $user->getId(), Zend_Auth::getInstance()->getIdentity()->id);
    }

    public function dialogsreadAction() {

        DatabaseObject_Pm::MarkAllAsRead($this->db, Zend_Auth::getInstance()->getIdentity()->id);
        $this->_redirect($this->getUrl('messages'));
    }

    public function dialogsalldeleteAction() {
        DatabaseObject_Pm::DeleteAll($this->db, Zend_Auth::getInstance()->getIdentity()->id);
        $this->_redirect($this->getUrl('messages'));
    }

    public function dialogdeleteAction() {
        $user = new DatabaseObject_User($this->db);
        $user->load($this->getRequest()->getParam('id'));
        DatabaseObject_Pm::DeleteDialog($this->db, $user->getId(), Zend_Auth::getInstance()->getIdentity()->id);
        $this->_redirect($this->getUrl('messages'));
    }

    public function sendpmAction() {
        $id = $this->getRequest()->getPost('id');

        $pm = new DatabaseObject_Pm($this->db);
        $pm->author = Zend_Auth::getInstance()->getIdentity()->id;
        $pm->user = $id;
        $pm->text = $this->getRequest()->getPost('text');
        
        // отправим уведомление о новом личном сообщении
        $userNotificationConfig = new DatabaseObject_NotificationSettings($this->db);
        $userNotificationConfig->load($id, 'idUser');
        
        if($userNotificationConfig && $userNotificationConfig->new_pm == 1) {
            DatabaseObject_User::SendNotificationEmail($this->db, 'new_pm', $id);
        }

        $pm->save();
        $this->_redirect($this->getCustomUrl(array('id' => $id), 'viewdialog'));
    }

    ///////////////////////////////////////////////////////////////////
    /////////// конец работы с сообщениями ////////////////////////////
    ///////////////////////////////////////////////////////////////////
    public function activeAction() {
        $this->view->page_title = "Мои покупки";
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['cart_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['cart_sort'])) {
            $temp = explode(' ', $_SESSION['cart_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'date';
            $order = 'desc';
            $_SESSION['cart_sort'] = $sort . ' ' . $order;
        }
        $page = max(1, $this->getRequest()->getQuery('p'));
        $type = $this->getRequest()->getQuery('type');
        $limit = $this->configuration['item_count'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Orders::GetUserCount($this->db, Zend_Auth::getInstance()->getIdentity()->id, $type) / $limit);
        $category = DatabaseObject_Orders::GetBasket($this->db, array('order' => $_SESSION['cart_sort'], 'where' => "userId = " . Zend_Auth::getInstance()->getIdentity()->id, 'limit' => $limit, 'offset' => $offset), $type);
        // CustomControllerAction::pre($category);
        $pag = CustomControllerAction::Pag($pages, $page);
        $this->view->pages = $pag;
        $this->view->page = $page;
        $this->view->type = $type;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->categories = $category;
    }

    public function saleAction() {
        $this->view->page_title = "Мои продажи";
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['cart_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['cart_sort'])) {
            $temp = explode(' ', $_SESSION['cart_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'date';
            $order = 'desc';
            $_SESSION['cart_sort'] = $sort . ' ' . $order;
        }
        $page = max(1, $this->getRequest()->getQuery('p'));
        $type = $this->getRequest()->getQuery('type');
        $limit = $this->configuration['item_count'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Orders::GetShopCount($this->db, Zend_Auth::getInstance()->getIdentity()->id, $type) / $limit);
        $category = DatabaseObject_Orders::GetBasket($this->db, array('order' => $_SESSION['cart_sort'], 'where' => "shopId = " . Zend_Auth::getInstance()->getIdentity()->id, 'limit' => $limit, 'offset' => $offset), $type);
        // CustomControllerAction::pre($category);
        $pag = CustomControllerAction::Pag($pages, $page);
        $this->view->pages = $pag;
        $this->view->page = $page;
        $this->view->type = $type;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->categories = $category;
    }

    public function myordersAction() {
        $this->view->page_title = "Персональные заказы";
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['request_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['request_sort'])) {
            $temp = explode(' ', $_SESSION['request_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'id';
            $order = 'desc';
            $_SESSION['request_sort'] = $sort . ' ' . $order;
        }
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['item_count'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Persorder::GetUserCount($this->db, Zend_Auth::getInstance()->getIdentity()->id) / $limit);
        $category = DatabaseObject_Persorder::GetRequest($this->db, array('order' => $_SESSION['request_sort'], 'where' => "of = " . Zend_Auth::getInstance()->getIdentity()->id, 'limit' => $limit, 'offset' => $offset));
        // CustomControllerAction::pre($category);
        $pag = CustomControllerAction::Pag($pages, $page);
        $this->view->pages = $pag;
        $this->view->p = $page;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->categories = $category;
    }

    public function myordersshopAction() {
        $this->view->page_title = "Персональные заказы магазина";
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['request_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['request_sort'])) {
            $temp = explode(' ', $_SESSION['request_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'id';
            $order = 'desc';
            $_SESSION['request_sort'] = $sort . ' ' . $order;
        }
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['item_count'];
        $offset = ($page - 1) * $limit;
        $pages = ceil(DatabaseObject_Persorder::GetShopCount($this->db, Zend_Auth::getInstance()->getIdentity()->id) / $limit);
        $category = DatabaseObject_Persorder::GetRequest($this->db, array('order' => $_SESSION['request_sort'], 'where' => "shopId = " . Zend_Auth::getInstance()->getIdentity()->id, 'limit' => $limit, 'offset' => $offset));
        // CustomControllerAction::pre($category);
        $pag = CustomControllerAction::Pag($pages, $page);
        $this->view->pages = $pag;
        $this->view->p = $page;
        $this->view->sort = $sort;
        $this->view->order = $order;
        $this->view->categories = $category;
    }

    public function zakazAction() {

        $id = $this->getRequest()->getParam('id');
        $zakaz = new DatabaseObject_Orders($this->db);
        $zakaz->load($id);
        // echo '<pre>';print_r($zakaz);echo '</pre>';
        $this->view->zakaz = $zakaz;
        $this->view->page_title = "Просмотр заказа";
    }

    public function updatezakazAction() {
        $id = $this->getRequest()->getParam('id');
        $stat = $this->getRequest()->getParam('stat');
        $zakaz = new DatabaseObject_Orders($this->db);
        $zakaz->load($id);
        // echo '<pre>';print_r($zakaz);echo '</pre>';
        $zakaz->status = $stat;
        $zakaz->save();
        echo 'ok';
        exit;
        // $this->view->zakaz = $zakaz;
    }

    public function deletezakazAction() {
        $id = $this->getRequest()->getParam('id');
        $users = new DatabaseObject_Orders($this->db);
        $users->load($id);
        $users->delete();
        echo 'ok';
        exit;
    }

    public function notificationsettingsAction() {
        $settings = DatabaseObject_NotificationSettings::GetSettings($this->db, Zend_Auth::getInstance()->getIdentity()->id);

        if ($this->getRequest()->isPost()) {
            
        }

        $this->view->settings = $settings;
    }

    public function favoriteAction() {
        $status = 'wish';

        $category = DatabaseObject_Basket::GetUserBascket($this->db, Zend_Auth::getInstance()->getIdentity()->id, $status);
        //   echo '<pre>';print_r($category);echo '</pre>';

        $this->view->categories = $category;
    }

    ///////////////////////////////////////////////////////////////////////////
    ///////// Интеркасса ////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    public function paywaysAction() {
        $this->view->page_title = "Выбор тарифа";
        $tarif = DatabaseObject_Tarif::GetTarifs($this->db);
        $this->view->tarif = $tarif;
    }

    public function privatqueryAction() {

        $this->view->page_title = "Оплата с помощью приват24";
        $this->view->key = $this->configuration['key'];
        $tarif_id = $this->getRequest()->getParam('tarif');
        $month = $this->getRequest()->getParam('period');
        //    $cur =  $val1 = Zend_Registry::get('db')->fetchOne("SELECT flag FROM currency WHERE id='".Zend_Auth::getInstance()->getIdentity()->currency."' "); 
        $pr = DatabaseObject_Tarif::GetPriceTarif($this->db, $tarif_id);
        $this->view->pr = $pr;
        $this->view->month = $month;
        $pr1 = $month * $pr->price;

        $private_key = $this->configuration['secret_key'];
        $param = array(
            'public_key' => 'i68292718518',
            'private_key' => '5OwfUQJ1A0OBINq3XOOcHEyR8sPia3A0sXnnPJEA',
            'order_id' => Zend_Auth::getInstance()->getIdentity()->id . '#' . $month . '#' . time(),
            'amount' => $pr1,
            'currency' => "UAH", // Zend_Registry::get('db')->fetchOne("SELECT flag FROM currency WHERE id='".Zend_Auth::getInstance()->getIdentity()->id."'"),//'UAH',
            'description' => "Абонентская плата торговой площадки DabaHM",
            'result_url' => "http://" . Zend_Registry::get('config')->domain . "/account/privatsuccess",
            'server_url' => 'http://' . Zend_Registry::get('config')->domain . '/account/privatstatus',
            'type' => "buy"
        );
        $signature = base64_encode(sha1(
                        $param['private_key'] .
                        $param['amount'] .
                        $param['currency'] .
                        $param['public_key'] .
                        $param['order_id'] .
                        $param['type'] .
                        $param['description'] .
                        $param['result_url'] .
                        $param['server_url'], 1));

        $this->view->signature = $signature;
        $this->view->param = $param;
    }

    public function privatstatusAction() {
        //  if ($this->getRequest()->getParam('status')) { die(); }
        $call = array(
            $_POST['amount'],
            $_POST['currency'],
            $_POST['public_key'],
            $_POST['description'],
            $_POST['order_id'],
            $_POST['type'],
            $_POST['status'],
            $_POST['transaction_id'],
            $_POST['sender_phone'],
            $_POST['signature'],
        );

        list(
                $amount,
                $currency,
                $public_key,
                $description,
                $order_id,
                $type,
                $status,
                $transaction_id,
                $sender_phone,
                $insig
                ) = $call;
        $real_order_id = explode('#', $order_id);

        $private_key = '5OwfUQJ1A0OBINq3XOOcHEyR8sPia3A0sXnnPJEA';

        $gensig = base64_encode(sha1(join('', compact(
                                        'private_key', 'amount', 'currency', 'public_key', 'order_id', 'type', 'description', 'status', 'transaction_id', 'sender_phone'
                        )), 1));

        // if ($insig != $gensig) { die(); }
        $pr = DatabaseObject_Tarif::GetPriceTarif($this->db, $real_order_id['1']);
        $month = $amount / $pr->price;
        if ($status == 'success') {
            $id = $real_order_id['0'];
            $tarif = $real_order_id['1'];
            $pay = new DatabaseObject_User($this->db);
            $pay->load(Zend_Auth::getInstance()->getIdentity()->id);
            $pay->isCreateProduct = 1;
            $pay->save();
            unset($pay);
           $query = ("INSERT INTO `pay` (`status`,`date`,`userId`,`tarif`,`month`,`phone`,`price`,`payId`,`date_end`,`flag`) "
                    . " VALUES ('$status','" . date('Y-m-d H:i:s') . "','$id','$tarif', '$month', '$sender_phone','$amount','$transaction_id','" . date('Y-m-d H:i:s') . "','1')");
            $this->db->query($query);
         /*   $shop = new DatabaseObject_Shop($this->db);
            $shop->load($id);
            $shop->plimit = $pr->count_product;
            $shop->payflag = 1;
            $shop->data_end = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s'))) . " +" . $month . " month"));
            $shop->save();
            unset($shop);*/
        }
        if ($status == 'sandbox') {
            $id = $real_order_id['0'];
            $tarif = $real_order_id['1'];
            $pay = new DatabaseObject_User($this->db);
            $pay->load($id);
            $pay->isCreateProduct = 1;
            $pay->save();
            unset($pay);
            $query = ("INSERT INTO `pay` (`status`,`date`,`userId`,`tarif`,`month`,`phone`,`price`,`payId`,`date_end`,`flag`) "
                    . " VALUES ('$status','" . date('Y-m-d H:i:s') . "','$id','$tarif','$month','$sender_phone','$amount','$transaction_id','" . date('Y-m-d H:i:s') . "','1')");
            $this->db->query($query);
           /* $shop = new DatabaseObject_Shop($this->db);
            $shop->load($id);

            $shop->plimit = $pr->count_product;
            $shop->payflag = 1;
            $shop->data_end = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s'))) . " +" . $month . " month"));

            $shop->save();
            unset($shop);*/
        }
    }

    public function privatsuccessAction() {
        
    }

    public function interkassapendingAction() {
        
    }

    public function interkassafailAction() {
        
    }

    ///////////////////////////////////////////////////////////////////////////
    ////////////////Интеркасса/////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
}

?>
